package springsecurityrabclogin.handler;

import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWTUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import springsecurityrabclogin.constant.Constant;
import springsecurityrabclogin.entity.TUser;
import springsecurityrabclogin.result.R;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 登录成功，会执行该方法
 */
@Slf4j
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    //直接注入RedisTemplate就可以操作redis，类的反省分别是放入数据的key的类型和value的类型
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException {
        AuthenticationSuccessHandler.super.onAuthenticationSuccess(request, response, chain, authentication);
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("/application/json");
        response.setCharacterEncoding("utf-8");

        //生成jwt (token)
        TUser tUser = (TUser) authentication.getPrincipal();
        String userJSON = JSONUtil.toJsonStr(tUser);
//        System.out.println("tUser object: " + tUser); // 或用日志框架记录

        String token = JWTUtil.createToken(Map.of("user",userJSON), Constant.SECRET.getBytes(StandardCharsets.UTF_8));

        //写入redis (五种值的结构类型 string, hash, list ,set ,zset)
        redisTemplate.opsForValue();//操作string
        redisTemplate.opsForHash();//操作hash
        redisTemplate.opsForList();//操作list
        redisTemplate.opsForSet();//操作set
        redisTemplate.opsForZSet();//操作zset

        //token适合使用string或者hash结构进行存储
        redisTemplate.opsForHash().put(Constant.REDIS_TOKEN_KEY,String.valueOf(tUser.getId()),token);

//        String redisToken = (String) redisTemplate.opsForHash().get(Constant.REDIS_TOKEN_KEY,tUser.getId());
//        System.out.println(redisToken);

        //采用构建器模式，链式编程创建一个R对象
        R result = R.builder().code(200).msg("登录成功").info(token).build();

        //利用hutool工具包，把R对象转成字符串
        String json = JSONUtil.toJsonStr(result);

        //把json写出去，写出到浏览器客户端
        response.getWriter().write(json);
    }
}
